package cn.edu.wzut;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

@Controller
public class LoginController {
    @RequestMapping("/login")
    public String showLogin(Model model, HttpServletRequest request){
        model.addAttribute("loginBean", new LoginBean());
        //生成随机数相加的表达式
        Random random = new Random();

        int n1 = random.nextInt(9) + 1;
        int n2 = random.nextInt(9) + 1;

        HttpSession session = request.getSession();
        session.setAttribute("captcha_result", n1 + n2);

        model.addAttribute("captcha_expr", Integer.toString(n1) + " + " + Integer.toString(n2));
        model.addAttribute("captcha_value", "");
        return "login.html";
    }

    @RequestMapping(value="/doLogin", method = RequestMethod.POST)
    public String doLogin(LoginBean loginBean, String captchaValue, Model model, HttpServletRequest request){
        HttpSession session = request.getSession();
        int captchaResult = (int) session.getAttribute("captcha_result");
        if("admin".equals(loginBean.getUserName()) && "pass".equals(loginBean.getPassword()) && captchaResult == Integer.parseInt(captchaValue)){
            session.setAttribute("userName", loginBean.getUserName());
            return "redirect:/home";
        }
        else
            return "redirect:/fail";
    }

    @RequestMapping(value="/home")
    public String showHome(){
        return "home.html";
    }

    @RequestMapping(value="/fail")
    public String showError(){
        return "fail.html";
    }

}
